package com.sihai.ehr.service.impl;

import com.sihai.core.DataAccessor;
import com.sihai.core.Limit;
import com.sihai.core.LimitedList;
import com.sihai.core.Sorter;
import com.sihai.ehr.model.sys.Resource;
import com.sihai.ehr.service.ResourceService;
import com.sihai.ehr.utils.ExcelUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.io.File;
import java.util.List;

/**
 * author: wxn
 * since: 13-2-4 Time: 上午11:31
 */
@Service("resourceService")
public class ResourceServiceImpl implements ResourceService {
    @javax.annotation.Resource
    private DataAccessor dataAccessor;

    @Override
    public Resource get(Long id) {
        Assert.notNull(id, "role id is required");
        return dataAccessor.get(Resource.class, id);
    }

    @Override
    public void save(Resource resource) {
        Assert.notNull(resource, "role is required");
        dataAccessor.save(resource);
    }

    @Override
    public LimitedList<Resource> find(Resource resource, Limit limit, Sorter sorter) {
        if(resource == null){
            return dataAccessor.findByHql(Resource.class, "from Resource", null, limit, sorter);
        }
        return null;
    }

    @Override
    public void delete(Long id) {
        Resource resource = get(id);
        Assert.notNull(resource, "resource is required");
        dataAccessor.delete(resource);
    }

    //初始化资源
    @Override
    public void initResource(File file) {
        List<String[]> rows = ExcelUtils.readExcel(file, 0, 1);
        if(rows == null || rows.isEmpty()){
            return;
        }
        for(String[] row : rows){
            com.sihai.ehr.model.sys.Resource resource = new com.sihai.ehr.model.sys.Resource();
            resource.setName(row[1]);
            resource.setMenuUrl(row[2]);
            resource.setUrl(row[3]);
            dataAccessor.save(resource);
        }
    }
}
